/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.IllegalOrphanException;
import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Storage;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.Component;
import it.polimi.games.epkb.entityClasses.Rack;
import it.polimi.games.epkb.entityClasses.DiskArray;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class StorageJpaController implements Serializable {


    public StorageJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

    public StorageJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Storage storage) throws IllegalOrphanException, PreexistingEntityException, Exception {
        if (storage.getDiskArrayCollection() == null) {
            storage.setDiskArrayCollection(new ArrayList<DiskArray>());
        }
        List<String> illegalOrphanMessages = null;
        Component componentOrphanCheck = storage.getComponent();
        if (componentOrphanCheck != null) {
            Storage oldStorageOfComponent = componentOrphanCheck.getStorage();
            if (oldStorageOfComponent != null) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("The Component " + componentOrphanCheck + " already has an item of type Storage whose component column cannot be null. Please make another selection for the component field.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Component component = storage.getComponent();
            if (component != null) {
                component = em.getReference(component.getClass(), component.getId());
                storage.setComponent(component);
            }
            Rack IDRack = storage.getIDRack();
            if (IDRack != null) {
                IDRack = em.getReference(IDRack.getClass(), IDRack.getId());
                storage.setIDRack(IDRack);
            }
            Collection<DiskArray> attachedDiskArrayCollection = new ArrayList<DiskArray>();
            for (DiskArray diskArrayCollectionDiskArrayToAttach : storage.getDiskArrayCollection()) {
                diskArrayCollectionDiskArrayToAttach = em.getReference(diskArrayCollectionDiskArrayToAttach.getClass(), diskArrayCollectionDiskArrayToAttach.getId());
                attachedDiskArrayCollection.add(diskArrayCollectionDiskArrayToAttach);
            }
            storage.setDiskArrayCollection(attachedDiskArrayCollection);
            em.persist(storage);
            if (component != null) {
                component.setStorage(storage);
                component = em.merge(component);
            }
            if (IDRack != null) {
                IDRack.getStorageCollection().add(storage);
                IDRack = em.merge(IDRack);
            }
            for (DiskArray diskArrayCollectionDiskArray : storage.getDiskArrayCollection()) {
                Storage oldIdStorageOfDiskArrayCollectionDiskArray = diskArrayCollectionDiskArray.getIdStorage();
                diskArrayCollectionDiskArray.setIdStorage(storage);
                diskArrayCollectionDiskArray = em.merge(diskArrayCollectionDiskArray);
                if (oldIdStorageOfDiskArrayCollectionDiskArray != null) {
                    oldIdStorageOfDiskArrayCollectionDiskArray.getDiskArrayCollection().remove(diskArrayCollectionDiskArray);
                    oldIdStorageOfDiskArrayCollectionDiskArray = em.merge(oldIdStorageOfDiskArrayCollectionDiskArray);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findStorage(storage.getId()) != null) {
                throw new PreexistingEntityException("Storage " + storage + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Storage storage) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Storage persistentStorage = em.find(Storage.class, storage.getId());
            Component componentOld = persistentStorage.getComponent();
            Component componentNew = storage.getComponent();
            Rack IDRackOld = persistentStorage.getIDRack();
            Rack IDRackNew = storage.getIDRack();
            Collection<DiskArray> diskArrayCollectionOld = persistentStorage.getDiskArrayCollection();
            Collection<DiskArray> diskArrayCollectionNew = storage.getDiskArrayCollection();
            List<String> illegalOrphanMessages = null;
            if (componentNew != null && !componentNew.equals(componentOld)) {
                Storage oldStorageOfComponent = componentNew.getStorage();
                if (oldStorageOfComponent != null) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("The Component " + componentNew + " already has an item of type Storage whose component column cannot be null. Please make another selection for the component field.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (componentNew != null) {
                componentNew = em.getReference(componentNew.getClass(), componentNew.getId());
                storage.setComponent(componentNew);
            }
            if (IDRackNew != null) {
                IDRackNew = em.getReference(IDRackNew.getClass(), IDRackNew.getId());
                storage.setIDRack(IDRackNew);
            }
            Collection<DiskArray> attachedDiskArrayCollectionNew = new ArrayList<DiskArray>();
            for (DiskArray diskArrayCollectionNewDiskArrayToAttach : diskArrayCollectionNew) {
                diskArrayCollectionNewDiskArrayToAttach = em.getReference(diskArrayCollectionNewDiskArrayToAttach.getClass(), diskArrayCollectionNewDiskArrayToAttach.getId());
                attachedDiskArrayCollectionNew.add(diskArrayCollectionNewDiskArrayToAttach);
            }
            diskArrayCollectionNew = attachedDiskArrayCollectionNew;
            storage.setDiskArrayCollection(diskArrayCollectionNew);
            storage = em.merge(storage);
            if (componentOld != null && !componentOld.equals(componentNew)) {
                componentOld.setStorage(null);
                componentOld = em.merge(componentOld);
            }
            if (componentNew != null && !componentNew.equals(componentOld)) {
                componentNew.setStorage(storage);
                componentNew = em.merge(componentNew);
            }
            if (IDRackOld != null && !IDRackOld.equals(IDRackNew)) {
                IDRackOld.getStorageCollection().remove(storage);
                IDRackOld = em.merge(IDRackOld);
            }
            if (IDRackNew != null && !IDRackNew.equals(IDRackOld)) {
                IDRackNew.getStorageCollection().add(storage);
                IDRackNew = em.merge(IDRackNew);
            }
            for (DiskArray diskArrayCollectionOldDiskArray : diskArrayCollectionOld) {
                if (!diskArrayCollectionNew.contains(diskArrayCollectionOldDiskArray)) {
                    diskArrayCollectionOldDiskArray.setIdStorage(null);
                    diskArrayCollectionOldDiskArray = em.merge(diskArrayCollectionOldDiskArray);
                }
            }
            for (DiskArray diskArrayCollectionNewDiskArray : diskArrayCollectionNew) {
                if (!diskArrayCollectionOld.contains(diskArrayCollectionNewDiskArray)) {
                    Storage oldIdStorageOfDiskArrayCollectionNewDiskArray = diskArrayCollectionNewDiskArray.getIdStorage();
                    diskArrayCollectionNewDiskArray.setIdStorage(storage);
                    diskArrayCollectionNewDiskArray = em.merge(diskArrayCollectionNewDiskArray);
                    if (oldIdStorageOfDiskArrayCollectionNewDiskArray != null && !oldIdStorageOfDiskArrayCollectionNewDiskArray.equals(storage)) {
                        oldIdStorageOfDiskArrayCollectionNewDiskArray.getDiskArrayCollection().remove(diskArrayCollectionNewDiskArray);
                        oldIdStorageOfDiskArrayCollectionNewDiskArray = em.merge(oldIdStorageOfDiskArrayCollectionNewDiskArray);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = storage.getId();
                if (findStorage(id) == null) {
                    throw new NonexistentEntityException("The storage with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Storage storage;
            try {
                storage = em.getReference(Storage.class, id);
                storage.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The storage with id " + id + " no longer exists.", enfe);
            }
            Component component = storage.getComponent();
            if (component != null) {
                component.setStorage(null);
                component = em.merge(component);
            }
            Rack IDRack = storage.getIDRack();
            if (IDRack != null) {
                IDRack.getStorageCollection().remove(storage);
                IDRack = em.merge(IDRack);
            }
            Collection<DiskArray> diskArrayCollection = storage.getDiskArrayCollection();
            for (DiskArray diskArrayCollectionDiskArray : diskArrayCollection) {
                diskArrayCollectionDiskArray.setIdStorage(null);
                diskArrayCollectionDiskArray = em.merge(diskArrayCollectionDiskArray);
            }
            em.remove(storage);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Storage> findStorageEntities() {
        return findStorageEntities(true, -1, -1);
    }

    public List<Storage> findStorageEntities(int maxResults, int firstResult) {
        return findStorageEntities(false, maxResults, firstResult);
    }

    private List<Storage> findStorageEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Storage.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Storage findStorage(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Storage.class, id);
        } finally {
            em.close();
        }
    }

    public int getStorageCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Storage> rt = cq.from(Storage.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
